package com.ruoyi.project.oms.paeaAuBatch.controller;

import java.util.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.project.oms.paeaAuAuditItem.domain.PaeaAuAuditItem;
import com.ruoyi.project.oms.paeaAuAuditItem.enums.AuditItemState;
import com.ruoyi.project.oms.paeaAuAuditItem.service.IPaeaAuAuditItemService;
import com.ruoyi.project.oms.paeaAuBatch.enums.AuBatchStatus;
import com.ruoyi.project.oms.paeaAuBatch.model.PaeaAuBatchRequest;
import com.ruoyi.project.oms.paeaAuTaskAssignManner.domain.PaeaAuTaskAssignManner;
import com.ruoyi.project.oms.paeaAuTaskAssignManner.service.IPaeaAuTaskAssignMannerService;
import com.ruoyi.project.oms.paeaAuType.service.IPaeaAuTypeService;
import com.ruoyi.project.system.dept.domain.Dept;
import com.ruoyi.project.system.dept.service.IDeptService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.oms.paeaAuBatch.domain.PaeaAuBatch;
import com.ruoyi.project.oms.paeaAuBatch.service.IPaeaAuBatchService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;
import javax.servlet.http.HttpServletRequest;

/**
 * 监督批次Controller
 *
 * @author ruoyi
 * @date 2020-03-24
 */
@Controller
@RequestMapping("/oms/paeaAuBatch")
public class PaeaAuBatchController extends BaseController {
    private String prefix = "oms/paeaAuBatch";

    @Autowired
    private IPaeaAuBatchService paeaAuBatchService;
    @Autowired
    private IPaeaAuTaskAssignMannerService paeaAuTaskAssignMannerService;
    @Autowired
    private IDeptService deptService;
    @Autowired
    private IPaeaAuAuditItemService paeaAuAuditItemService;
    @Autowired
    private IPaeaAuTypeService paeaAuTypeService;

    @RequiresPermissions("oms:paeaAuBatch:view")
    @GetMapping()
    public String paeaAubatch(ModelMap mmap) {
        mmap.put("auTypes", paeaAuTypeService.selectPaeaAuTypeAll());
        return prefix + "/paeaAuBatch";
    }

    /**
     * 查询监督批次列表
     */
    @RequiresPermissions("oms:paeaAuBatch:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(PaeaAuBatch paeaAuBatch) {
        startPage();
        List<PaeaAuBatch> list = paeaAuBatchService.list(new QueryWrapper<PaeaAuBatch>(paeaAuBatch)
        .eq("status",200)
        .ne("auditor_id",getLoginName())
        .orderByAsc("tr_date"));
        return getDataTable(list);
    }

    /**
     * 查询监督批次列表
     */
    @RequiresPermissions("oms:paeaAuBatch:queryList")
    @PostMapping("/queryList")
    @ResponseBody
    public TableDataInfo queryList(PaeaAuBatchRequest paeaAuBatchRequest) {
        int batchType = 0;
        if (paeaAuBatchRequest.getBatchType() != null) {
            batchType = paeaAuBatchRequest.getBatchType();
        }
        String statusS = paeaAuBatchRequest.getStatus();
        int status = 0;
        if (statusS != null && !"".equals(statusS)) {
            status = Integer.valueOf(statusS).intValue();
        }
        List<PaeaAuTaskAssignManner> taskAssignManners = paeaAuTaskAssignMannerService.list();
        String manner = "";
        if (null != taskAssignManners && taskAssignManners.size() > 0) {
            manner = taskAssignManners.get(0).getManner();
        }
        startPage();
        List<PaeaAuBatch> list = paeaAuBatchService.queryPaeaAuBatchs(paeaAuBatchRequest.getOrgId(), batchType,
                paeaAuBatchRequest.getBeginDate(), paeaAuBatchRequest.getEndDate(), status, manner, paeaAuBatchRequest.getQueryFlag(), paeaAuBatchRequest.getAuditorId());
        return getDataTable(list);
    }

    /**
     * 导出监督批次列表
     */
    @RequiresPermissions("oms:paeaAuBatch:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(PaeaAuBatch paeaAuBatch) {
        List<PaeaAuBatch> list = paeaAuBatchService.list(new QueryWrapper<>(paeaAuBatch));
        ExcelUtil<PaeaAuBatch> util = new ExcelUtil<PaeaAuBatch>(PaeaAuBatch.class);
        return util.exportExcel(list, "paeaAuBatch");
    }

    /**
     * 新增监督批次
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存监督批次
     */
    @RequiresPermissions("oms:paeaAuBatch:add")
    @Log(title = "监督批次", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(PaeaAuBatch paeaAuBatch) {
        return toAjax(paeaAuBatchService.saveOrUpdate(paeaAuBatch));
    }

    /**
     * 修改监督批次
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap) {
        PaeaAuBatch paeaAuBatch = paeaAuBatchService.getById(id);
        mmap.put("paeaAuBatch", paeaAuBatch);
        return prefix + "/edit";
    }

    /**
     * 修改保存监督批次
     */
    @RequiresPermissions("oms:paeaAuBatch:edit")
    @Log(title = "监督批次", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(PaeaAuBatch paeaAuBatch) {
        return toAjax(paeaAuBatchService.saveOrUpdate(paeaAuBatch));
    }

    /**
     * 删除监督批次
     */
    @RequiresPermissions("oms:paeaAuBatch:remove")
    @Log(title = "监督批次", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(paeaAuBatchService.removeByIds(Arrays.asList(ids.split(","))));
    }

    /**
     * 新增监督批次
     */
    @RequestMapping("/paeaAuBatchForQuery")
    public String paeaAuBatchForQuery(ModelMap mmap,@RequestParam(name = "queryFlag") String queryFlag) {
        String userId = getLoginName();
        mmap.addAttribute("queryFlag", queryFlag);
        mmap.addAttribute("userId", userId);
        return prefix + "/paeaAuBatchForQuery";
    }

    /**
     * 随机获取监督批次
     *
     * @param paeaAuBatchRequest
     * @param mmap
     * @param request
     * @return
     */
    @RequiresPermissions("oms:paeaAuBatch:obtainByIdRandom")
    @PostMapping("/obtainByIdRandom")
    @ResponseBody
    public AjaxResult obtainByIdRandom(PaeaAuBatchRequest paeaAuBatchRequest, ModelMap mmap, HttpServletRequest request) {
        String queryFlag = paeaAuBatchRequest.getQueryFlag();
        int status = AuBatchStatus.Initial.getValue();
        paeaAuBatchRequest.setStatus(String.valueOf(status));
        List<PaeaAuTaskAssignManner> taskAssignManners = paeaAuTaskAssignMannerService.list();
        String manner = "";
        if (null != taskAssignManners && taskAssignManners.size() > 0) {
            manner = taskAssignManners.get(0).getManner();
        }
        String userId = getLoginName();
        List<PaeaAuBatch> list = paeaAuBatchService.queryPaeaAuBatchs("", 0,
                null, null, status, manner, queryFlag, userId);
        if (list == null || list.size() < 1) {
            status = AuBatchStatus.Partially_Audited.getValue();
            list = paeaAuBatchService.queryPaeaAuBatchs("", 0,
                    null, null, status, manner, queryFlag, userId);
        }
        String returnString = "";
        String titleContext = "";
        if (list.size() < 1) {
            return AjaxResult.warn("没有可获取的预警处理内容");
        } else {
            PaeaAuBatch batch = (PaeaAuBatch) list.get(0);
            Dept dept = deptService.selectDeptById(batch.getOrgId());
            titleContext = batch.getOrgId() + "-" + batch.getBatchType() + "-" + (dept == null ? "" : dept.getDeptName());
            //分表查询待定
            List<PaeaAuAuditItem> paeaAuAuditItems = paeaAuAuditItemService.queryItemForBatchId(batch.getId());
            returnString = paeaAuBatchService.obtainReturnString(batch.getId(),
                    titleContext, true, paeaAuAuditItems);
        }
        AjaxResult ajax = AjaxResult.success();
        ajax.put("returnString", returnString);
        return ajax;
    }

    /**
     * 通过Id 手工获取监督任务
     * @param paeaAuBatchRequest
     * @return
     */
    @RequiresPermissions("oms:paeaAuBatch:obtainById")
    @PostMapping("/obtainById")
    @ResponseBody
    public AjaxResult obtainById(PaeaAuBatchRequest paeaAuBatchRequest) {
        String auBatchId = paeaAuBatchRequest.getId();
        //监控数据的记录
        PaeaAuBatch batch = paeaAuBatchService.selectPaeaAuBatchById(auBatchId);
        String titleContext = "";
        if (null != batch) {
            Dept dept = deptService.selectDeptById(batch.getOrgId());
            titleContext = batch.getOrgId() + "-" + batch.getBatchType() + "-" + (dept==null?"":dept.getDeptName());
            //分表查询
            List<PaeaAuAuditItem> items = paeaAuAuditItemService.queryItemForBatchId(auBatchId);
            String returnString =paeaAuBatchService.obtainReturnString(auBatchId,titleContext, false, items);
             AjaxResult ajax = AjaxResult.success();
             ajax.put("returnString",returnString);
             return ajax;
        } else {
            return AjaxResult.error("未找到相应批次");
        }
    }

    /**
     * 提交监控批次
     *paeaAuBatchRequest
     * @return
     */
    @RequiresPermissions("oms:paeaAuBatch:submitAuBatch")
    @PostMapping("/submitAuBatch")
    @ResponseBody
    public AjaxResult submitAuBatch(PaeaAuBatchRequest paeaAuBatchRequest) {
        //获取基本信息
        String batchId = paeaAuBatchRequest.getId();
        //java.util.Date trDate = paeaAuBatchRequest.getTrDate();
        String queryFlag = paeaAuBatchRequest.getQueryFlag();
        String userCode = getLoginName();
        PaeaAuBatch batch = paeaAuBatchService.selectPaeaAuBatchById(batchId);
        batch.setAuditorId(userCode);
        //分表查询
        List<PaeaAuAuditItem> items = paeaAuAuditItemService.queryItemForBatchId(batchId);
        String returnString = "0";
        AjaxResult ajax = AjaxResult.success();
        try { // TODO:写工作日志 submit
            int unAuditNum = paeaAuAuditItemService.submit(batch,items,userCode,queryFlag);
            //还存在未监控的
            if(unAuditNum > 0){
                returnString = "" + unAuditNum;
            }
            ajax.put("returnString",returnString);
        } catch (Throwable e) {
            e.printStackTrace();
            AjaxResult.error("提交写工作量日志出错");
        }
        return ajax;
    }

}
